﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DrugStorehouseMIS.BLL;
using DrugStorehouseMIS.Comm;

namespace DrugStorehouseMIS.StockInAndOutManager
{
    public partial class frmStockOut : Form
    {
        private StockOutHeader stockOutHeaderBLL;
        private StockOutDetail stockOutDetailBLL;
        private StockOutType stockOutTypeBLL;
        private Manager managerBLL;
        private Inventory inventoryBLL;
        private GridPrinter gridPrinter;

        public frmStockOut()
        {
            InitializeComponent();

            stockOutHeaderBLL = new StockOutHeader();
            stockOutDetailBLL = new StockOutDetail();
            stockOutTypeBLL = new StockOutType();

            stockOutHeaderBLL.DepartmentName = new Department();
            stockOutHeaderBLL.StockOutTypeName = new StockOutType();
            stockOutDetailBLL.DrugNum = new Drug();

            managerBLL = new Manager();
            inventoryBLL = new Inventory();
        }

        private void frmStockOut_Load(object sender, EventArgs e)
        {
            BindStockOutType();
            LoadDataGridViewHeader();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tabStockOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabStockOut.SelectedTab.Text == "出库单明细")
            {
                LoadDataGridViewDetail();
            }
            else if (tabStockOut.SelectedTab.Text == "出库单汇总")
            {
                LoadDataGridViewHeader();
            }
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            bool more = gridPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }

      
        #region 出库单汇总

        /// <summary>
        /// 设置header打印的相关信息
        /// </summary>
        /// <returns></returns>
        private bool InitHeaderPrinting()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != DialogResult.OK)
            {
                return false;
            }
            printDocument.DocumentName = "入库汇总单";
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.DefaultPageSettings = printDialog.PrinterSettings.DefaultPageSettings;
            printDocument.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(40, 40, 40, 40);
            gridPrinter = new GridPrinter(dgvStockOutHeader, printDocument, true, true, "出库汇总单", new Font("黑体", 24, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);


            return true;
        }


        public void BindStockOutType()
        {
            IList<StockOutType> list = stockOutTypeBLL.GetAllStockOutType();
            foreach (StockOutType obj in list)
            {
                cbxFilterStockOutType.Items.Add(obj.StockOutTypeName);
            }
            cbxFilterStockOutType.SelectedIndex = 0;
        }

        /// <summary>
        /// 加载header信息
        /// </summary>
        public void LoadDataGridViewHeader()
        {
            dgvStockOutHeader.DataSource = stockOutHeaderBLL.Filter(txtFilterStockOutNum.Text.Trim(), cbxFilterStockOutType.Text, txtFilterDepartment.Text.Trim(), GetStatus());
            //dgvStockOutHeader.DataSource = stockOutHeaderBLL.DisplayByStatus(GetStatus());
            if (dgvStockOutHeader.Rows.Count > 0 && GetStatus() == "未审核")
            {
                tsBtnOutHeaderEdit.Enabled = true;
                tsBtnOutHeaderDelete.Enabled = true;
                tsBtnOutHeaderConfirm.Enabled = true;
            }
            else
            {
                tsBtnOutHeaderConfirm.Enabled = false;
                tsBtnOutHeaderDelete.Enabled = false;
                tsBtnOutHeaderEdit.Enabled = false;
            }

            Tool.ResetAllTextBox(gbxOutHeaderInfo);  //清空textbox信息
            rtbInfoOutHeaderRemark.Text = "";
        }

        /// <summary>
        /// 获取当前选中的状态
        /// </summary>
        /// <returns></returns>
        public string GetStatus()
        {
            if (rdbNoApproval.Checked == true)
            {
                return rdbNoApproval.Text;
            }
            else
            {
                return rdbAlreadyApproval.Text;
            }
        }

        /// <summary>
        /// 获取选中行的对象
        /// </summary>
        /// <returns></returns>
        public StockOutHeader GetHeaderRowObject()
        {
            StockOutHeader header = new StockOutHeader();
            header.StockOutTypeName = new StockOutType();
            header.DepartmentName = new Department();

            if (dgvStockOutHeader.CurrentRow.Index >= 0)
            {
                header.ApprovalBy = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["ApprovalBy"].Value.ToString();
                header.CreatedBy = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["CreatedBy"].Value.ToString();
                header.DepartmentName.DepartmentName = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["Department"].Value.ToString();
                header.Remark = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["Remark"].Value.ToString();
                header.Status = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["Status"].Value.ToString();
                header.StockOutDatetime = Convert.ToDateTime(dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["StockOutDate"].Value);
                header.StockOutNum = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["HeaderStockOutNum"].Value.ToString();
                header.StockOutTypeName.StockOutTypeName = dgvStockOutHeader.Rows[dgvStockOutHeader.CurrentRow.Index].Cells["StockOutType"].Value.ToString();
            }

            return header;
        }

        private void rdbNoApproval_CheckedChanged(object sender, EventArgs e)
        {
            LoadDataGridViewHeader();
            if (rdbNoApproval.Checked == true && dgvStockOutHeader.Rows.Count > 0)
            {
                tsBtnOutHeaderConfirm.Enabled = tsBtnOutHeaderDelete.Enabled = tsBtnOutHeaderEdit.Enabled = true;
            }
            else
            {
                tsBtnOutHeaderConfirm.Enabled = tsBtnOutHeaderDelete.Enabled = tsBtnOutHeaderEdit.Enabled = false;
            }
        }

        private void tsBtnOutHeaderNew_Click(object sender, EventArgs e)
        {
            frmStockOutHeaderNew form = new frmStockOutHeaderNew();
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewHeader();
            }
        }

        private void tsBtnOutHeaderEdit_Click(object sender, EventArgs e)
        {
            frmStockOutHeaderEdit form = new frmStockOutHeaderEdit();
            form.Init(GetHeaderRowObject());
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewHeader();
            }
        }

        private void tsBtnOutHeaderDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                stockOutHeaderBLL.RemoveStockOutHeader(GetHeaderRowObject());      //已通过存储过程里删除对应的detail
                LoadDataGridViewHeader();
            }    
        }

        private void tsBtnOutHeaderConfirm_Click(object sender, EventArgs e)
        {
            StockOutHeader header = new StockOutHeader();
            header.DepartmentName = new Department();
            header.StockOutTypeName = new StockOutType();
            IList<StockOutDetail> list = new List<StockOutDetail>();
            header = this.GetHeaderRowObject();
            list = stockOutDetailBLL.GetStockOutDetailAll(header.StockOutNum);
            DialogResult result = MessageBox.Show("确定审核吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                header.Status = "已审核";
                header.ApprovalBy = frmMain.userObject.UserName; //获取登录用户
                stockOutHeaderBLL.SetStockOutHeader(header);     //更新状态

                managerBLL.ConfirmStockOut(header, list);
                LoadDataGridViewHeader();
            }       
        }

        private void tsBtnOutHeaderPrint_Click(object sender, EventArgs e)
        {
            if (InitHeaderPrinting())
            {
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.Document = printDocument;
                printPreviewDialog.ShowDialog();
            }
        }

        private void dgvStockOutHeader_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                txtInfoOutHeaderNum.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["HeaderStockOutNum"].Value.ToString();
                txtInfoOutHeaderType.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["StockOutType"].Value.ToString();
                txtInfoOutHeaderDate.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["StockOutDate"].Value.ToString();
                txtInfoOutHeaderDepartment.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["Department"].Value.ToString();
                txtInfoOutHeaderCreatedBy.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["CreatedBy"].Value.ToString();
                txtInfoOutHeaderApprovalBy.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["ApprovalBy"].Value.ToString();
                rtbInfoOutHeaderRemark.Text = dgvStockOutHeader.Rows[e.RowIndex].Cells["Remark"].Value.ToString();
            }
        }

        #endregion

        #region 出库单明细

        /// <summary>
        /// 设置detail打印的相关信息
        /// </summary>
        /// <returns></returns>
        private bool InitDetailPrinting()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != DialogResult.OK)
            {
                return false;
            }
            printDocument.DocumentName = "入库明细单";
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.DefaultPageSettings = printDialog.PrinterSettings.DefaultPageSettings;
            printDocument.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(40, 40, 40, 40);
            gridPrinter = new GridPrinter(dgvStockOutDetail, printDocument, true, true, "出库明细单", new Font("黑体", 24, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);


            return true;
        }


        /// <summary>
        /// 获取当前选中行的detail
        /// </summary>
        /// <returns></returns>
        public StockOutDetail GetDetailRowObject()
        {
            StockOutDetail detail = new StockOutDetail();
            detail.DrugNum = new Drug();

            detail.Amount = Convert.ToSingle(dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["Amount"].Value);
            detail.StockOutNum = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["StockOutNum"].Value.ToString();
            detail.DrugNum.DrugNum = Convert.ToInt32(dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["DrugNum"].Value);
            detail.OutportPrice = Convert.ToSingle(dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["OutportPrice"].Value);
            detail.RealQuantity = Convert.ToInt32(dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["RealQuantity"].Value);

            return detail;
        }

        /// <summary>
        /// 加载对应单号的明细记录，并作好各按钮的可用状态
        /// </summary>
        public void LoadDataGridViewDetail()
        {
            if (dgvStockOutHeader.Rows.Count > 0)
            {
                StockOutHeader header = this.GetHeaderRowObject();
                dgvStockOutDetail.DataSource = stockOutDetailBLL.GetStockOutDeatilByNum(header.StockOutNum);
               
                if (header.Status == "已审核" || dgvStockOutDetail.Rows.Count < 0)
                {
                    tsBtnOutDetailDelete.Enabled = false;
                    tsBtnOutDetailEdit.Enabled = false;
                }
            }
            else
            {
                tsBtnOutDetailDelete.Enabled = false;
                tsBtnOutDetailEdit.Enabled = false;
            }

            Tool.ResetAllTextBox(gbxOutHeaderInfo);
        }

        private void tsBtnOutDetailNew_Click(object sender, EventArgs e)
        {
            frmStockOutDetailNew form = new frmStockOutDetailNew();
            form.Init(GetHeaderRowObject());
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewDetail();
            }
        }

        private void tsBtnOutDetailEdit_Click(object sender, EventArgs e)
        {
            frmStockOutDetailEdit form = new frmStockOutDetailEdit();
            StockOutHeader header = new StockOutHeader();
            StockOutDetail detial = new StockOutDetail();
            string aDrugName, aSpecifications, aMeasuringUnit, aTradePrice, aRetailPrice, aStockQuantity;

            header = this.GetHeaderRowObject();
            detial = this.GetDetailRowObject();
            aDrugName = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["TradeName"].Value.ToString();
            aSpecifications = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["Specifications"].Value.ToString();
            aMeasuringUnit = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["MeasuringUnit"].Value.ToString();
            aTradePrice = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["TradePrice"].Value.ToString();
            aRetailPrice = dgvStockOutDetail.Rows[dgvStockOutDetail.CurrentRow.Index].Cells["RetailPrice"].Value.ToString();
            aStockQuantity = inventoryBLL.GetStockQuantity(detial.DrugNum.DrugNum).ToString();

            form.Init(header, detial, aDrugName, aSpecifications, aMeasuringUnit, aTradePrice, aRetailPrice,aStockQuantity);
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewDetail();
            }
        }

        private void tsBtnOutDetailDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if(result==DialogResult.OK)
            {
                stockOutDetailBLL.RemoveStockOutDetail(GetDetailRowObject().StockOutNum, GetDetailRowObject().DrugNum.DrugNum);
                LoadDataGridViewDetail();
            }
        }

        private void tsBtnOutDetailPrint_Click(object sender, EventArgs e)
        {
            if (InitDetailPrinting())
            {
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.Document = printDocument;
                printPreviewDialog.ShowDialog();
            } 
        }

        private void dgvStockOutDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                txtInfoOutAmount.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["Amount"].Value.ToString();
                txtInfoOutDrugName.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["TradeName"].Value.ToString();
                txtInfoOutMeasuringUnit.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["MeasuringUnit"].Value.ToString();
                txtInfoOutOutportPrice.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["OutportPrice"].Value.ToString();
                txtInfoOutQutntity.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["RealQuantity"].Value.ToString();
                txtInfoOutRetailPrice.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["RetailPrice"].Value.ToString();
                txtInfoOutSpecifications.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["Specifications"].Value.ToString();
                txtInfoOutStockOutNum.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["StockOutNum"].Value.ToString();
                txtInfoOutTradePrice.Text = dgvStockOutDetail.Rows[e.RowIndex].Cells["TradePrice"].Value.ToString();
            }
        }
       
        #endregion

        #region 查询
        private void cbxFilterStockOutType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataGridViewHeader();
        }

        private void txtFilterStockOutNum_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadDataGridViewHeader();
            }
        }

        private void txtFilterDepartment_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadDataGridViewHeader();
            }
        }

        #endregion                  
    }
}